package com.shd.edanpei.util.contact;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;

import com.shd.edanpei.util.IntentUtils;
import com.shd.edanpei.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * Created by mc on 2018/11/15.
 * 设备通讯录导入工具
 */

public class DeviceContactsImportTools {

    private Activity activity;
    private RxPermissions rxPermissions;
    private List<ContactBean> contactsList = new ArrayList<>();
    private Callback callback;

    public DeviceContactsImportTools(Activity activity) {
        this.activity = activity;
        rxPermissions = new RxPermissions(activity);
    }

    public void startLead(Callback callback) {
        this.callback = callback;
        //检查权限
        rxPermissions.request(Manifest.permission.READ_CONTACTS)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //权限已开启
                            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                            builder.setTitle("导入确认")
                                    .setMessage("您确定要导入手机通讯录吗？")
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("导入", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
//                                            readContacts();
                                            new MyTask().execute();
                                            dialog.dismiss();

                                        }
                                    }).show();
                        } else {
                            //权限未开启&&用户选择了禁止提醒
                            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                            builder.setTitle("开启权限")
                                    .setMessage("访问通讯录权限被禁止，请到权限设置中打开！")
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            activity.startActivity(IntentUtils.getAppDetailSettingIntent());
                                            dialog.dismiss();
                                        }
                                    })
                                    .show();
                        }
                    }
                });

    }

    private void readContacts() {


    }

    public interface Callback {

        void start();

        void done(List<ContactBean> list);
    }

    private class MyTask extends AsyncTask {

        /**
         * 作用：执行 线程任务前的操作
         */
        @Override
        protected void onPreExecute() {
            callback.start();
        }

        /**
         * @param objects
         * @return
         */
        @Override
        protected Object doInBackground(Object[] objects) {
            contactsList.clear();
            Cursor cursor = null;
            try {
                //查询联系人数据,使用了getContentResolver().query方法来查询系统的联系人的数据
                //CONTENT_URI就是一个封装好的Uri，是已经解析过得常量
                cursor = activity.getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        null,
                        null,
                        null
                );
                //对cursor进行遍历，取出姓名和电话号码
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        //获取联系人姓名
                        String displayName = cursor.getString(cursor.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                        ));
                        //获取联系人手机号
                        String number = cursor.getString(cursor.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER
                        ));
                        //把取出的两类数据进行拼接，中间加换行符，然后添加到listview中
                        contactsList.add(new ContactBean(displayName, number));
                    }
                    //刷新listview
//                adapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //记得关掉cursor
                if (cursor != null) {
                    cursor.close();
                }
            }
            return null;
        }

        /**
         * 作用：在主线程 显示线程任务执行的进度
         *
         * @param values
         */
        @Override
        protected void onProgressUpdate(Object[] values) {

        }

        /**
         * 作用：接收线程执行结果
         *
         * @param o
         */
        @Override
        protected void onPostExecute(Object o) {
            if (callback != null) {
                callback.done(contactsList);
            }
        }
    }
}
